package com.amigo.online.provider.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.dto.pay.CardPayDto;
import com.amigo.online.common.param.dto.pay.IosPayDto;
import com.amigo.online.common.param.dto.vip.PayVipDto;
import com.amigo.online.common.param.result.VipChatInfo;
import com.amigo.online.common.param.result.VipInfo;
import com.amigo.online.provider.user.exception.UserException;
import com.amigo.online.provider.user.mapper.UserMapper;
import com.amigo.online.provider.user.mapper.VipChatMapper;
import com.amigo.online.provider.user.mapper.VipMemberTblMapper;
import com.amigo.online.provider.user.mapper.VipPriceTblMapper;
import com.amigo.online.provider.user.model.entity.VipChat;
import com.amigo.online.provider.user.model.entity.VipMemberTbl;
import com.amigo.online.provider.user.model.entity.VipPriceTbl;
import com.amigo.online.provider.user.mongo.dao.UserDao;
import com.amigo.online.provider.user.mongo.entity.UserEntity;
import com.amigo.online.provider.user.service.PayService;
import com.amigo.online.provider.user.service.VIPService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author pangdonghao
 * @version 1.0
 * @csdn https://blog.csdn.net/pangdongh
 * @createDate 2019/10/22 10:33
 */
@Service
@Slf4j
public class VIPServiceImpl implements VIPService {

    @Autowired
    VipMemberTblMapper vipMemberTblMapper;
    @Autowired
    VipPriceTblMapper vipPriceTblMapper;
    @Autowired
    VipChatMapper vipChatMapper;
    @Autowired
    PayService payService;
    @Autowired
    UserDao userDao;
    /**
     * 买VIP
     * @param payVipDto
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void payVip(PayVipDto payVipDto) {
        VipPriceTbl vipPriceTbl = vipPriceTblMapper.selectByPrimaryKey(payVipDto.getVipPriceId());
        if(vipPriceTbl == null){
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        //支付前置操作
        rechargeVip(vipPriceTbl);

        CardPayDto payDto = JSONObject.parseObject(JSONObject.toJSONString(payVipDto), CardPayDto.class);
        payDto.setPaymentId(genId());
        payDto.setPayMoney(vipPriceTbl.getDiscountPrice());
        payDto.setInfo("购买会员");
        payDto.setUserId(LocalUser.getUser().getUser().getId());
        payDto.setCommodityType(1);
        //支付
        JSONObject jsonObject = payService.payWithCard(payDto);
        if(!jsonObject.getBoolean("success")){
            throw new UserException(StatusCode.PAY_ERROR);
        }
    }
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void payVipByIOS(String base64) {


        IosPayDto payDto = new IosPayDto();
        payDto.setInfo("购买会员");
        payDto.setUserId(LocalUser.getUser().getUser().getId());
        payDto.setCommodityType(1);
        payDto.setBase64(base64);
        //支付
        String product_id = payService.payWithIOS(payDto);
        if(product_id == null){
            throw new UserException(StatusCode.PAY_ERROR);
        }
        VipPriceTbl vipPriceTbl = new VipPriceTbl();
        vipPriceTbl.setIosId(product_id);
        vipPriceTbl = vipPriceTblMapper.selectOne(vipPriceTbl);
        if(vipPriceTbl == null){
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        //支付前置操作
        rechargeVip(vipPriceTbl);
    }
    /**
     * 创建速推业务订单号
     *
     * @return
     */
    public static String genId(){
        String orderId =
                (System.currentTimeMillis() + "") +
                        (System.nanoTime() + "").substring(7, 10);
        System.out.println(orderId);
        return orderId;
    }

    /**
     * 充值VIP 不包含支付
     * @param vipPriceTbl
     */
    private void rechargeVip(VipPriceTbl vipPriceTbl){
        VipMemberTbl vipMemberTbl = getVip();
        if(vipMemberTbl == null){//现在没会员
            VipMemberTbl myVipMemberTbl =new VipMemberTbl();
            myVipMemberTbl.setUserId(LocalUser.getUser().getUser().getId());
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.DATE, vipPriceTbl.getDay());
            // 时
            cal.set(Calendar.HOUR_OF_DAY, 23);
            // 分
            cal.set(Calendar.MINUTE, 59);
            // 秒
            cal.set(Calendar.SECOND, 59);
            log.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()));
            myVipMemberTbl.setStartTime(new Date());
            myVipMemberTbl.setEndTime(cal.getTime());
            myVipMemberTbl.setChatNum(-1);
            myVipMemberTbl.setEnd(false);
            myVipMemberTbl.setType(vipPriceTbl.getId());
            vipMemberTblMapper.insertSelective(myVipMemberTbl);

            Update update = new Update().set("vip", 1).set("vipEndTime",cal.getTime());
            userDao.updateUserInfo(LocalUser.getUser().getUser().getId(),update);
        }else {//现在有会员,进入续费流程(只更新时间)
            Calendar cal = Calendar.getInstance();
            cal.setTime(vipMemberTbl.getEndTime());
            cal.add(Calendar.DATE, vipPriceTbl.getDay());
            // 时
            cal.set(Calendar.HOUR_OF_DAY, 23);
            // 分
            cal.set(Calendar.MINUTE, 59);
            // 秒
            cal.set(Calendar.SECOND, 59);
            vipMemberTbl.setEndTime(cal.getTime());
            vipMemberTbl.setEnd(false);
            vipMemberTblMapper.updateByPrimaryKeySelective(vipMemberTbl);
        }
    }
    /**
     * 获取没结束的VIP信息(每个用户end状态为false的记录只能有一条)
     * @return
     */
    @Override
    public VipMemberTbl getVip(){

        return  getVipByUserId(LocalUser.getUser().getUser().getId());
    }

    @Override
    public boolean isVip(long userId) {
        if (getVipByUserId(userId)!=null){
            return true;
        }
        return false;
    }

    @Override
    public VipInfo getVipInfo(long userId){
        VipMemberTbl vipMemberTbl = getVipByUserId(userId);
        if(vipMemberTbl !=null){
            VipInfo vipInfo = JSONObject.parseObject(JSONObject.toJSONString(vipMemberTbl), VipInfo.class);
            VipPriceTbl vipPriceTbl = vipPriceTblMapper.selectByPrimaryKey(vipMemberTbl.getType());
            vipInfo.setType(vipPriceTbl.getId());
            vipInfo.setVip(true);
            Locale locale = LocaleContextHolder.getLocale();
            String language = locale.getLanguage();
            if("zh".equals(language)){//中文
                vipInfo.setTypeName(vipPriceTbl.getNameCn());
            }else if("en".equals(language)){//英语
                vipInfo.setTypeName(vipPriceTbl.getNameEn());
            }else if("pt".equals(language)){//葡萄牙
                vipInfo.setTypeName(vipPriceTbl.getNamePt());
            }else if("es".equals(language)){//葡萄牙
                vipInfo.setTypeName(vipPriceTbl.getNameEs());
            }else {
                vipInfo.setTypeName(vipPriceTbl.getNameEn());
            }
            return vipInfo;
        }else {
            return new VipInfo().setVip(false);
        }

    }
    @Override
    public VipChatInfo vipChat(Long userId){
        long myUserId = LocalUser.getUser().getUser().getId();
        VipMemberTbl vipMemberTbl = getVip();
        if(vipMemberTbl!= null){
            VipChat vipChat = new VipChat();
            vipChat.setUserId(myUserId);
            vipChat.setRecipientId(userId);
            VipChat vipChat1 = vipChatMapper.selectOne(vipChat);
            if(vipChat1!=null){//已经和这个用户聊过天
                return new VipChatInfo().setCanChat(true).setChatNum(vipMemberTbl.getChatNum());
            }else {//没聊过天
                if(vipMemberTbl.getChatNum()!=0){
                    //聊天次数减一
                    vipMemberTblMapper.reduceChatNum(vipMemberTbl.getId());
                    return new VipChatInfo().setCanChat(true).setChatNum(vipMemberTbl.getChatNum() == -1 ? vipMemberTbl.getChatNum(): vipMemberTbl.getChatNum()-1);
                }
                //聊天次数不足
                return new VipChatInfo().setCanChat(false).setInfo(2);
            }
        }else {//不是会员
            return new VipChatInfo().setCanChat(false).setInfo(1);
        }

    }
    public VipMemberTbl getVipByUserId(long id){
        VipMemberTbl vipMemberTbl = new VipMemberTbl();
        vipMemberTbl.setUserId(id);
        vipMemberTbl.setEnd(false);

        return vipMemberTblMapper.selectOne(vipMemberTbl);
    }
}
